package cn.edu.henu.team.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.ninegrid.ImageInfo;
import java.io.File;
import java.util.ArrayList;
import androidx.appcompat.app.AlertDialog;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.bean._User;
import cn.edu.henu.team.bean.post;
import cn.edu.henu.team.base.BaseActivity;
import cn.edu.henu.team.utils.myImageLoader;

public class AddPostingActivity extends BaseActivity {
    private ImageView back;
    private String imagePath = null;
    private BmobFile image_file;
    private ArrayList<ImageItem> imageItems;  //因为布局不熟，目前先是一张图片吧
    private TextView publish;
    private ImageView Saying_image;
    private EditText Saying_topic_edittext;
    private EditText Saying_content_edittext;

    private String Saying_topic;
    private String Saying_content;

    @Override
    protected int initLayout() {
        return R.layout.activity_add_posting;
    }

    @Override
    protected void initView() {
        back =  findViewById(R.id.back);
        publish = findViewById(R.id.publish);
        Saying_image =findViewById(R.id.Saying_image);
        Saying_topic_edittext =  findViewById(R.id.Saying_topic);
        Saying_content_edittext =  findViewById(R.id.Saying_content);
    }


    @Override
    protected void initData() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Saying_topic = Saying_topic_edittext.getText().toString();
                Saying_content = Saying_content_edittext.getText().toString();
                if (Saying_topic.equals("") && Saying_content.equals(""))
                    finish();
                else {
                    createDialog();
                }
            }
        });

        Saying_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开相册进行选择
                addImage(1);
            }
        });

        publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Saying_content = Saying_content_edittext.getText().toString();
                if (Saying_content.equals(""))
                    Toast.makeText(getApplicationContext(), "内容为空，无法发布", Toast.LENGTH_SHORT).show();
                else
                    deliverSaying();//发表帖子
            }
        });
    }

    public void createDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setMessage("内容无法保存，确定离开？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).create();
        alertDialog.show();
    }


    /*
     *发布帖子
     */
    public void deliverSaying() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(true);
        progressDialog.setMessage("正在发布中...");
        progressDialog.show();
        _User user = BmobUser.getCurrentUser(_User.class);
        Saying_topic = Saying_topic_edittext.getText().toString();
        Saying_content = Saying_content_edittext.getText().toString();
        // 创建帖子信息
        final post add_post = new post();
        add_post.setUserId(user);// 添加一对一关联
        add_post.setUserOnlyId(user.getObjectId());
        add_post.setTopic(Saying_topic);
        add_post.setContent(Saying_content);
        add_post.setPraise(0);
        // 查看需不需要上传图片
        if (imagePath != null) {
            image_file = new BmobFile(new File(imagePath));
            //要先上传图片，之后才能将图片加载到新建数据列里
            image_file.uploadblock(new UploadFileListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        add_post.setImage(image_file);
                        add_post.save(new SaveListener<String>() {
                            @Override
                            public void done(String objectId, BmobException e) {
                                if(e==null){
                                    Toast.makeText(getApplicationContext(), "发布成功", Toast.LENGTH_SHORT).show();
                                    progressDialog.dismiss();
                                    finish();
                                }else{
                                    Toast.makeText(getApplicationContext(), "发布失败", Toast.LENGTH_SHORT).show();
                                    progressDialog.dismiss();
                                }
                            }
                        });
                    } else {
                        Toast.makeText(getApplication(), "发布失败", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                }
            });
        } else {
            add_post.save(new SaveListener<String>() {
                @Override
                public void done(String objectId, BmobException e) {
                    if(e==null){
                        Toast.makeText(getApplicationContext(), "发布成功", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                        finish();
                        overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
                    }else{
                        Toast.makeText(getApplicationContext(), "发布失败", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                }
            });
        }
    }

    /*
     *访问相册上传照片
     */
    private void addImage(Integer imageNum) {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new myImageLoader());
        imagePicker.setMultiMode(false);   //多选
        imagePicker.setSelectLimit(imageNum);    //最多选择X张
        imagePicker.setCrop(true);       //不进行裁剪
        Intent intent = new Intent(AddPostingActivity.this, ImageGridActivity.class);
        startActivityForResult(intent, 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String[] filePaths = new String[imageItems.size()];
                filePaths[0] = imageItems.get(0).path;
                imagePath = filePaths[0];
                Log.d("path",imagePath);
                Glide.with(this).load(imagePath).into(Saying_image);
            }else {
                showToastInThread(getApplicationContext(),"没有选择图片呢! ");
            }
        }
    }
}